//
//  CYTabBar.swift
//  MySina
//
//  Created by mac on 2017/1/16.
//  Copyright © 2017年 xinyuan. All rights reserved.
//

import UIKit

//代理01 - 定义代理协议
protocol CYTabBarDelegate: NSObjectProtocol {
    //代理02 - 定义代理方法
    func composeButtonDidClick()
}

class CYTabBar: UITabBar {

    //定义闭包
    var closure:(() -> ())?
    //代理03 -  定义代理属性
    weak var CYDelegate: CYTabBarDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(composeButton)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //设置UITabBarButton宽度
        let w = SCREENW * 0.2
        
        //设置UITabBarButton的位置
        var index: CGFloat = 0
        
        for view in subviews {
            if view.isKind(of: NSClassFromString("UITabBarButton")!) {
                view.frame.size.width = w
                view.frame.origin.x = index * w
                index += 1
                if index == 2 {
                    index += 1
                }
                
            }
            
        }
        
        //设置按钮frame
        composeButton.center.x = frame.width * 0.5
        composeButton.center.y = frame.height * 0.5
        
    }
    // MARK: - 懒加载控价,添加按钮
    private lazy var composeButton : UIButton = {
        //定义一个btn
        let btn = UIButton()
        btn.addTarget(self, action: #selector(buttonClick), for: UIControlEvents.touchUpInside)
        //设置image
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), for: UIControlState.normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        
        //设置背景图片
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: UIControlState.normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        btn.sizeToFit()
        return btn
    }()
    
    @objc private func buttonClick() {
        //执行闭包
        closure?()
        //代理04 - 执行代理方法
        CYDelegate?.composeButtonDidClick()
    }
    
}
